package lock;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class SimpleCache {

    public static void main(String[] args) {
        ArrayList<String> arrayList = new ArrayList<String>(50);

        for (int i = 0; i < 50; i++) {
            Thread thread = new Thread(() -> {
                for (int j = 0; j < 10; j++) {
                    arrayList.add(Thread.currentThread().getId() + "-" + j);
                    SimpleCache.putItem(Thread.currentThread().getId() + "-" + j,
                            String.valueOf(System.currentTimeMillis()));
                }
            });
            thread.start();
        }

        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        for (String s : arrayList) {
            System.out.println(s + ":" + SimpleCache.getItem(s));
        }
    }

    private static Map<String, Object> cacheMap = new HashMap<>();
    private static ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock(false);
    static Lock rLock = rwLock.readLock();
    static Lock wLock = rwLock.writeLock();

    static boolean putItem(String cacheKey, Object cacheItem) {

        boolean success;
        wLock.lock();
        try {
            success = cacheMap.put(cacheKey, cacheItem) != null;
        } finally {
            wLock.unlock();
        }
        return success;

    }

    static boolean removeItem(String cacheKey, Object cacheItem) {
        boolean success;
        wLock.lock();
        try {
            success = cacheMap.remove(cacheKey) != null;
        } finally {
            wLock.unlock();
        }
        return success;
    }


    static Object getItem(String cacheKey) {
        Object obj = null;
        rLock.lock();
        try {
            obj = cacheMap.get(cacheKey);
        } finally {
            rLock.unlock();
        }
        return obj;
    }
}
